package com.base.core.framework;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.base.core.framework.PropertyFilter.MatchType;
import com.base.utils.ReflectionUtils;

public class BaseDao<T> extends SimpleHibernateDao<T, Serializable> {
	/**
	 * 主键属性名
	 */
	public static final String PK = "id";
	
	/**
	 * 跨数据库改造 特殊字符
	 */
	public static final String WHERE = " where ";
	
	/** 日志对象 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 
	 * 创建一个新的实例 BaseDao.
	 * 
	 */
	public BaseDao() {

	}

	/**
	 * 
	 * 创建一个新的实例 BaseDao.
	 * 
	 * @param sessionFactory
	 *            hibernate会话工厂
	 * @param entityClass
	 *            实体的类
	 */
	public BaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
		super(sessionFactory, entityClass);
	}
	
	/**
	 * 多表关联查询时，取出某种类型的实体作为列表返回
	 * @param clz
	 * @param hql
	 * @param values
	 * @return
	 */
	protected List<T> findListByClass(Class<T> clz, String hql, Object... values)
	{
		List<T> nls = new ArrayList();
		List<Object[]> ls = find(hql, values);
		for(Object[] o : ls){
			for(int i = 0;i < o.length;i++){
				if(o[i].getClass().equals(clz)){
					nls.add((T)o[i]);
					break;
				}
			}
		}
		return nls;
	}

	// -- 分页查询函数 --//
	/**
	 * 分页获取全部对象.
	 * 
	 * @param page
	 *            page
	 * @return 返回全部
	 */
	public PageResult<T> getAll(final Page page) {
		return findPage(page);
	}
	
	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数.不支持其中的orderBy参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            数量可变的查询参数,按顺序绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public PageResult<T> findPage(Page page, final String hql,
			final Object... values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);
		long totalCount = 0;
		if (page.autoCount) {
			totalCount = countHqlResult(hql, values);
			page.recordTotal = totalCount;
		}

		setPageParameter(q, page);
		List result = q.list();
		// 过滤由于所选的页码不符合查询结果，则更改页码为起始页码进行查询校准
		if (result.size() == 0 && totalCount != 0) {
			q.setFirstResult(0);
			q.setMaxResults(page.recordPerPage);
			result = q.list();
			page.currentPage = 1;
		}
		PageResult<T> pr = new PageResult<T>();
		pr.page = page;
		pr.result = result;
		return pr;
	}
	
	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            命名参数,按名称绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public PageResult<T> findPage(Page page, final String hql,
			final Map<String, Object> values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);
		long totalCount = 0;
		if (page.autoCount) {
			totalCount = countHqlResult(hql, values);
			page.recordTotal = totalCount;
		}

		setPageParameter(q, page);

		List result = q.list();
		// 过滤由于所选的页码不符合查询结果，则更改页码为起始页码进行查询校准
		if (result.size() == 0 && totalCount != 0) {
			q.setFirstResult(0);
			q.setMaxResults(page.recordPerPage);
			result = q.list();
			page.currentPage = 1;
		}
		PageResult<T> pr = new PageResult<T>();
		pr.page = page;
		pr.result = result;
		return pr;
	}

	/**
	 * 根据过滤参数进行分页查询
	 * 
	 * @param page
	 *            页面对象
	 * @param propertyFilterMap
	 *            形式如(key="EQS_xxxfieldName")
	 * @return 页面对象
	 * @see PropertyFilter
	 */
	@Transactional(readOnly = true)
	@Deprecated
	public PageResult<T> findPage(final Page page, final Map<String, String> propertyFilterMap) {
		List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();

		// 分析参数Map,构造PropertyFilter列表
		for (Map.Entry<String, String> entry : propertyFilterMap.entrySet()) {
			String filterName = entry.getKey();
			Object value = entry.getValue();
			// 如果value值为空,则忽略此filter.
			if (value == null) {
				continue;
			}
			boolean omit = StringUtils.isBlank(value.toString());
			if (!omit) {
				PropertyFilter filter = new PropertyFilter(filterName, value);
				filterList.add(filter);
			}
		}
		Criterion[] criterions = buildPropertyFilterCriterions(filterList);
		return findPage(page, criterions);
	}
	
	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildPropertyFilterCriterions(
			final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			if (!filter.isMultiProperty()) { // 只有一个属性需要比较的情况.
				Criterion criterion = buildPropertyFilterCriterion(filter
						.getPropertyName(), filter.getPropertyValue(), filter
						.getMatchType());
				criterionList.add(criterion);
			} else {// 包含多个属性需要比较的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				for (String param : filter.getPropertyNames()) {
					Criterion criterion = buildPropertyFilterCriterion(param,
							filter.getPropertyValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}

	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildPropertyFilterCriterion(final String propertyName,
			final Object propertyValue, final MatchType matchType) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;

		// 根据MatchType构造criterion
		if (MatchType.EQ.equals(matchType)) {
			criterion = Restrictions.eq(propertyName, propertyValue);
		} else if (MatchType.LIKE.equals(matchType)) {
			criterion = Restrictions.like(propertyName, (String) propertyValue,
					MatchMode.ANYWHERE);
		} else if (MatchType.LE.equals(matchType)) {
			criterion = Restrictions.le(propertyName, propertyValue);
		} else if (MatchType.LT.equals(matchType)) {
			criterion = Restrictions.lt(propertyName, propertyValue);
		} else if (MatchType.GE.equals(matchType)) {
			criterion = Restrictions.ge(propertyName, propertyValue);
		} else if (MatchType.GT.equals(matchType)) {
			criterion = Restrictions.gt(propertyName, propertyValue);
		}

		return criterion;
	}
	
	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param criterions
	 *            数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public PageResult<T> findPage(Page page, final Criterion... criterions) {
		Assert.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);
		long totalCount = 0;
		if (page.autoCount) {
			totalCount = countCriteriaResult(c);
			page.recordTotal = totalCount;
		}

		setPageParameter(c, page);
		List result = c.list();
		// 过滤由于所选的页码不符合查询结果，则更改页码为起始页码进行查询校准
		if (result.size() == 0 && totalCount != 0) {
			c.setFirstResult(0);
			c.setMaxResults(page.recordPerPage);
			result = c.list();
			page.currentPage = 1;
		}
		PageResult<T> pr = new PageResult<T>();
		pr.result = result;
		pr.page = page;
		return pr;
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameter(final Query q, final Page page) {
		// hibernate的firstResult的序号从0开始
		q.setFirstResult((page.currentPage - 1) * page.recordPerPage);
		q.setMaxResults(page.recordPerPage);
		return q;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 * 
	 * @param c
	 *            条件对象
	 */
	protected Criteria setPageParameter(final Criteria c, final Page page) {
		// hibernate的firstResult的序号从0开始
		c.setFirstResult((page.currentPage - 1) * page.recordPerPage);
		c.setMaxResults(page.recordPerPage);

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.orderBy, ',');
			String[] orderArray = StringUtils.split(page.order, ',');

			Assert.isTrue(orderByArray.length == orderArray.length,
					"分页多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					c.addOrder(Order.asc(orderByArray[i]));
				} else {
					c.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}
	

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	protected long countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl,
					"orderEntries");
			ReflectionUtils
					.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			// 此处出现异常不需要处理
			logger.error("Runtime Exception impossibility throw:{}", e
					.getMessage());
		}

		// 执行Count查询
		long totalCount = Long.valueOf( c.setProjection(Projections.rowCount())
				.uniqueResult().toString());

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			// 此处出现异常不需要处理
			logger.error("Runtime Exception impossibility throw:{}", e
					.getMessage());
		}

		return totalCount;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Object... values) {
		String fromHql = hql;
		// select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}
	

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Map<String, Object> values) {
		String fromHql = hql;
		// select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}


	/**
	 * 拷贝属性值到hibernate持久化实体的方式更新，不拷贝关联实体属性
	 * 
	 * @param entity
	 *            实体
	 */
	public void copyUpdate(T entity) {
		Assert.notNull(entity, "entity can not be null");

		Serializable id = (Serializable) ReflectionUtils.getFieldValue(entity, PK);
		T target = get(id);
		Assert.notNull(target, entity.getClass().getName() + "[id=" + id
				+ "] not exist！");

		// 复制更新持久化实体
		BeanUtils.copyProperties(entity, target, getAsscociationProperties());
	}

	/**
	 * 描述：获取关联属性 <br>
	 * 
	 * @param entity
	 * @return Serializable
	 * @Exception 异常对象 <br>
	 */
	public String[] getAsscociationProperties() {
		List<String> asscociationProperties = new ArrayList<String>();
		PropertyDescriptor[] entityPds = BeanUtils.getPropertyDescriptors(this.entityClass.getClass());
		for (int i = 0; i < entityPds.length; i++) {
			PropertyDescriptor entityPd = entityPds[i];
			Class clazz = entityPd.getPropertyType();
			if (Collection.class.isAssignableFrom(clazz) || clazz.isAnnotationPresent(Entity.class)) {
				asscociationProperties.add(entityPd.getName());
			}
		}
		return asscociationProperties.toArray(new String[0]);
	}

	/**
	 * 拷贝属性值到hibernate持久化实体的方式更新
	 * 
	 * @param entity
	 *            携带新的属性值的对象
	 * @param ignoreFields
	 *            无需拷贝的属性
	 */
	public void copyUpdate(T entity, String[] ignoreFields) {
		Assert.notNull(entity, "entity can not be null");

		Serializable id = (Serializable) ReflectionUtils.getFieldValue(entity, PK);
		T target = get(id);
		Assert.notNull(target, entity.getClass().getName() + "[id=" + id
				+ "] not exist！");

		// 复制更新持久化实体
		BeanUtils.copyProperties(entity, target, ignoreFields);
	}
}
